---
title: "COVID-19 no Brasil"
author: "Carlos Eduardo Veras Neves (adaptado de Antoine Soetewey)"
output:
flexdashboard::flex_dashboard:
orientation: rows
# social: ["facebook", "twitter", "linkedin"]
source_code: embed
vertical_layout: fill
---
```{r setup, include=FALSE}
#------------------ Packages ------------------
library(flexdashboard)
# install.packages("devtools")
# devtools::install_github("RamiKrispin/coronavirus")
library(coronavirus)
data(coronavirus)
update_datasets()
# View(coronavirus)
`%>%` <- magrittr::`%>%`
#------------------ Parameters ------------------
# Set colors
# https://www.w3.org/TR/css-color-3/#svg-color
confirmed_color <- "purple"
active_color <- "#1f77b4"
recovered_color <- "forestgreen"
death_color <- "red"
#------------------ Data ------------------
df <- coronavirus %>%
# dplyr::filter(date == max(date)) %>%
dplyr::filter(Country.Region == "Brazil") %>%
dplyr::group_by(Country.Region, type) %>%
dplyr::summarise(total = sum(cases)) %>%
tidyr::pivot_wider(
names_from = type,
values_from = total
) %>%
dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
dplyr::arrange(-confirmed) %>%
dplyr::ungroup() %>%
dplyr::mutate(country = dplyr::if_else(Country.Region == "United Arab Emirates", "UAE", Country.Region)) %>%
dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
dplyr::mutate(country = trimws(country)) %>%
dplyr::mutate(country = factor(country, levels = country))
df_daily <- coronavirus %>%
dplyr::filter(Country.Region == "Brazil") %>%
dplyr::group_by(date, type) %>%
dplyr::summarise(total = sum(cases, na.rm = TRUE)) %>%
tidyr::pivot_wider(
names_from = type,
values_from = total
) %>%
dplyr::arrange(date) %>%
dplyr::ungroup() %>%
dplyr::mutate(active = confirmed - death - recovered) %>%
dplyr::mutate(
confirmed_cum = cumsum(confirmed),
death_cum = cumsum(death),
recovered_cum = cumsum(recovered),
active_cum = cumsum(active)
)
df1 <- coronavirus %>% dplyr::filter(date == max(date))
```
Sumário
=======================================================================
Row {data-width=400}
-----------------------------------------------------------------------
### confirmed {.value-box}
```{r}
valueBox(
value = paste(format(sum(df$confirmed), big.mark = ".", decimal.mark = ","), "", sep = " "),
caption = "Número total de casos confirmados",
icon = "fas fa-user-md",
color = confirmed_color
)
```
### active {.value-box}
```{r}
valueBox(
value = paste(format(sum(df$unrecovered, na.rm = TRUE), big.mark = ".", decimal.mark = ","), " (",
round(100 * sum(df$unrecovered, na.rm = TRUE) / sum(df$confirmed), 1),
"%)",
sep = ""
),
caption = "Casos ativos (% do total de casos)", icon = "fas fa-ambulance",
color = active_color
)
```
### death {.value-box}
```{r}
valueBox(
value = paste(format(sum(df$death, na.rm = TRUE), big.mark = ".", decimal.mark = ","), " (",
round(100 * sum(df$death, na.rm = TRUE) / sum(df$confirmed), 1),
"%)",
sep = ""
),
caption = "Mortes (taxa de mortalidade)",
icon = "fas fa-heart-broken",
color = death_color
)
```
Row
-----------------------------------------------------------------------
### **Número de casos acumulados por tipo** (Brasil somente)
```{r}
plotly::plot_ly(data = df_daily) %>%
plotly::add_trace(
x = ~date,
y = ~active_cum,
type = "scatter",
mode = "lines+markers",
name = "Ativos",
line = list(color = active_color),
marker = list(color = active_color)
) %>%
plotly::add_trace(
x = ~date,
y = ~death_cum,
type = "scatter",
mode = "lines+markers",
name = "Mortes",
line = list(color = death_color),
marker = list(color = death_color)
) %>%
plotly::add_annotations(
x = as.Date("2020-02-26"),
y = 1,
text = paste("Primeiro caso"),
xref = "x",
yref = "y",
arrowhead = 5,
arrowhead = 3,
arrowsize = 1,
showarrow = TRUE,
ax = -10,
ay = -90
) %>%
plotly::add_annotations(
x = as.Date("2020-03-17"),
y = 3,
text = paste("Primeira morte"),
xref = "x",
yref = "y",
arrowhead = 5,
arrowhead = 3,
arrowsize = 1,
showarrow = TRUE,
ax = 90,
ay = -90
) %>%
plotly::add_annotations(
x = as.Date("2020-03-16"),
y = 14,
text = paste(
"Medidas de",
"
",
"contenção"
),
xref = "x",
yref = "y",
arrowhead = 5,
arrowhead = 3,
arrowsize = 1,
showarrow = TRUE,
ax = -20,
ay = -90
) %>%
plotly::layout(
title = "",
yaxis = list(title = "Número acumulado de casos"),
xaxis = list(title = "Data"),
legend = list(x = 0.1, y = 0.9),
hovermode = "compare"
)
```
Números comparados
=======================================================================
Column {data-width=400}
-------------------------------------
### **Novos casos diários**
```{r}
daily_confirmed <- coronavirus %>%
dplyr::filter(type == "confirmed") %>%
dplyr::filter(date >= "2020-02-29") %>%
dplyr::mutate(country = Country.Region) %>%
dplyr::group_by(date, country) %>%
dplyr::summarise(total = sum(cases)) %>%
dplyr::ungroup() %>%
tidyr::pivot_wider(names_from = country, values_from = total)
#----------------------------------------
# Plotting the data
daily_confirmed %>%
plotly::plot_ly() %>%
plotly::add_trace(
x = ~date,
y = ~Brazil,
type = "scatter",
mode = "lines+markers",
name = "Brasil"
) %>%
plotly::add_trace(
x = ~date,
y = ~France,
type = "scatter",
mode = "lines+markers",
name = "França"
) %>%
plotly::add_trace(
x = ~date,
y = ~Spain,
type = "scatter",
mode = "lines+markers",
name = "Espanha"
) %>%
plotly::add_trace(
x = ~date,
y = ~Italy,
type = "scatter",
mode = "lines+markers",
name = "Itália"
) %>%
plotly::layout(
title = "",
legend = list(x = 0.1, y = 0.9),
yaxis = list(title = "Número de novos casos confirmados (por dia)"),
xaxis = list(title = "Data"),
# paper_bgcolor = "black",
# plot_bgcolor = "black",
# font = list(color = 'white'),
hovermode = "compare",
margin = list(
# l = 60,
# r = 40,
b = 10,
t = 10,
pad = 2
)
)
```
### **Distribuição dos casos por tipo**
```{r daily_summary}
df_EU <- coronavirus %>%
# dplyr::filter(date == max(date)) %>%
dplyr::filter(Country.Region == "Brazil" |
Country.Region == "France" |
Country.Region == "Italy" |
Country.Region == "Spain") %>%
dplyr::group_by(Country.Region, type) %>%
dplyr::summarise(total = sum(cases)) %>%
tidyr::pivot_wider(
names_from = type,
values_from = total
) %>%
dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
dplyr::arrange(confirmed) %>%
dplyr::ungroup() %>%
dplyr::mutate(country = dplyr::if_else(Country.Region == "United Arab Emirates", "UAE", Country.Region)) %>%
dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
dplyr::mutate(country = trimws(country)) %>%
dplyr::mutate(country = factor(country, levels = country))
plotly::plot_ly(
data = df_EU,
x = ~country,
y = ~unrecovered,
# text = ~ confirmed,
# textposition = 'auto',
type = "bar",
name = "Casos Ativos",
marker = list(color = active_color)
) %>%
plotly::add_trace(
y = ~death,
# text = ~ death,
# textposition = 'auto',
name = "Mortes",
marker = list(color = death_color)
) %>%
plotly::layout(
barmode = "stack",
yaxis = list(title = "Total de casos"),
xaxis = list(title = ""),
hovermode = "compare",
margin = list(
# l = 60,
# r = 40,
b = 10,
t = 10,
pad = 2
)
)
```
Previsões para o Brasil
=======================================================================
Row {data-width=400}
-----------------------------------------------------------------------
### R0 {.value-box}
```{r}
library(deSolve)
Infected = daily_confirmed$Brazil[daily_confirmed$Brazil>0] #incidência
N = 211000000 # população Brasileira
Day <- 1:(length(Infected))
init <- c(S = N-Infected[1], I = Infected[1], R = 0)
RSS <- function(parameters) {
names(parameters) <- c("beta", "gamma")
out <- ode(y = init, times = Day, func = SIR, parms = parameters)
fit <- out[ , 3]
sum((Infected - fit)^2)
}
SIR <- function(time, state, parameters) {
par <- as.list(c(state, parameters))
with(par, {
dS <- -beta/N * I * S
dI <- beta/N * I * S - gamma * I
dR <- gamma * I
list(c(dS, dI, dR))
})
}
Opt <- optim(c(0.5, 0.5), RSS, method = "L-BFGS-B", lower = c(0, 0), upper = c(1, 1)) # optimize with some sensible conditions
#Opt$message
## [1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
Opt_par <- setNames(Opt$par, c("beta", "gamma"))
## Warning in xy.coords(x, y, xlabel, ylabel, log = log): 1 y value <= 0
## omitted from logarithmic plot
t <- 1:90 # time in days
fit <- data.frame(ode(y = init, times = t, func = SIR, parms = Opt_par))
col <- 1:3 # colour
R0 <- setNames(Opt_par["beta"] / Opt_par["gamma"], "R0")
## R0
## 2.073224
pico = fit[fit$I == max(fit$I), "I", drop = FALSE] # height of pandemic
## I
## 50 232001865
max_mortes = max(fit$I) * 0.02 # max deaths with supposed 2% fatality rate
## [1] 4640037
valueBox(
value = paste(format(round(R0,2), decimal.mark = ",")
),
caption = "Taxa Básica de Reprodução (R0)", icon = "fas fa-user-md",
color = active_color
)
```
### infectados_pico {.value-box}
```{r}
valueBox(
value = paste(format(pico, big.mark = ".", decimal.mark = ",")," (",
round(100 * pico / N, 1),
"%)",
sep = ""
),
caption = "Número máximo de infectados", icon = "fas fa-ambulance",
color = active_color
)
```
### mortes_pico {.value-box}
```{r}
valueBox(
value = paste(format(max_mortes, big.mark = ".", decimal.mark = ",")," (",
round(100 * max_mortes / N, 1),
"%)",
sep = ""
),
caption = "Número de mortos", icon = "fas fa-heart-broken",
color = active_color
)
```
Column {data-width=400}
-------------------------------------
### **Modelo de regressão linear para os novos casos diários (escala logarítmica) **
```{r}
library(zoo)
daily_confirmed10 <- coronavirus %>%
dplyr::filter(type == "confirmed") %>%
dplyr::filter(date >= "2020-02-29") %>%
dplyr::mutate(country = Country.Region) %>%
dplyr::group_by(date, country) %>%
dplyr::summarise(total = log(sum(cases))) %>%
dplyr::ungroup() %>%
tidyr::pivot_wider(names_from = country, values_from = total)
#----------------------------------------
# linear fit for data in log scale
fit_br = lm(Brazil ~ date, data = daily_confirmed10, subset=Brazil>0)
fit_sp = lm(Spain ~ date, data = daily_confirmed10, subset=Spain>0)
fit_it = lm(Italy ~ date, data = daily_confirmed10, subset=Spain>0)
fit_fr = lm(France ~ date, data = daily_confirmed10, subset=France>0)
#----------------------------------------
# Plotting the data
daily_confirmed10 %>%
plotly::plot_ly() %>%
#plotly::layout(yaxis = list(type = "log")) %>%
plotly::add_trace(
x = ~date,
y = ~Brazil,
type = "scatter",
mode = "markers",
name = "Brasil",
color=I('blue')
) %>%
plotly::add_lines(
x = ~date[as.numeric(names(fit_br$fitted.values))],
y = fitted(fit_br),
name="Brasil reg.linear",
color=I('blue')
) %>%
plotly::add_trace(
x = ~date,
y = ~France,
type = "scatter",
mode = "markers",
name = "França",
color=I('green')
) %>%
plotly::add_lines(
x = ~date[as.numeric(names(fit_fr$fitted.values))],
y = fitted(fit_fr),
name="França reg.linear",
color=I('green')
) %>%
plotly::add_trace(
x = ~date,
y = ~Spain,
type = "scatter",
mode = "markers",
name = "Espanha",
color=I('black')
) %>%
plotly::add_lines(
x = ~date[as.numeric(names(fit_sp$fitted.values))],
y = fitted(fit_sp),
name="Espanha reg.linear",
color=I('black')
) %>%
plotly::add_trace(
x = ~date,
y = ~Italy,
type = "scatter",
mode = "markers",
name = "Itália",
color=I('red')
) %>%
plotly::add_lines(
x = ~date[as.numeric(names(fit_it$fitted.values))],
y = fitted(fit_it),
name="Itália reg.linear",
color=I('red')
) %>%
plotly::layout(
title = "",
legend = list(x = .8, y = 0.1),
yaxis = list(title = "Número de novos casos confirmados (por dia) - Log"),
xaxis = list(title = "Data"),
# paper_bgcolor = "black",
# plot_bgcolor = "black",
# font = list(color = 'white'),
hovermode = "compare",
margin = list(
# l = 60,
# r = 40,
b = 10,
t = 10,
pad = 2
)
)
```
### **Modelo de Previsão (SIR) para o Brasil (população de 211 milhões)**
```{r }
#matplot(fit$time, fit[ , 2:4], type = "l", xlab = "Day", ylab = "Number of subjects", lwd = 2, lty = 1, col = col)
matplot(fit$time, fit[ , 2:4], type = "l", xlab = "Day", ylab = "Número de pessoas", lwd = 2, lty = 1, col = col, log = "y")
## Warning in xy.coords(x, y, xlabel, ylabel, log = log): 1 y value <= 0
## omitted from logarithmic plot
points(Day, Infected)
legend("bottomright", c("Suscetíveis", "Infectados", "Recuperados"), lty = 1, lwd = 2, col = col, inset = 0.05)
title("SIR modelo 2019-nCoV Brasil", outer = TRUE, line = -2)
```
Mapa
=======================================================================
### **Mapa mundial dos casos** (*use + e - para dar zoom in/out*)
```{r}
# map tab added by Art Steinmetz
library(leaflet)
library(leafpop)
library(purrr)
cv_data_for_plot <- coronavirus %>%
# dplyr::filter(Country.Region == "Belgium") %>%
dplyr::filter(cases > 0) %>%
dplyr::group_by(Country.Region, Province.State, Lat, Long, type) %>%
dplyr::summarise(cases = sum(cases)) %>%
dplyr::mutate(log_cases = 2 * log(cases)) %>%
dplyr::ungroup()
cv_data_for_plot.split <- cv_data_for_plot %>% split(cv_data_for_plot$type)
pal <- colorFactor(c("orange", "red", "green"), domain = c("confirmed", "death", "recovered"))
map_object <- leaflet() %>% addProviderTiles(providers$Stamen.Toner)
names(cv_data_for_plot.split) %>%
purrr::walk(function(df) {
map_object <<- map_object %>%
addCircleMarkers(
data = cv_data_for_plot.split[[df]],
lng = ~Long, lat = ~Lat,
# label=~as.character(cases),
color = ~ pal(type),
stroke = FALSE,
fillOpacity = 0.8,
radius = ~log_cases,
popup = leafpop::popupTable(cv_data_for_plot.split[[df]],
feature.id = FALSE,
row.numbers = FALSE,
zcol = c("type", "cases", "Country.Region", "Province.State")
),
group = df,
# clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F),
labelOptions = labelOptions(
noHide = F,
direction = "auto"
)
)
})
map_object %>%
addLayersControl(
overlayGroups = names(cv_data_for_plot.split),
options = layersControlOptions(collapsed = FALSE)
)
```